package com.zoe.onelink.feign.auth.token.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zoe.onelink.feign.auth.token.FeignTokenEncryptor;
import com.zoe.onelink.feign.auth.token.FeignTokenValidator;
import com.zoe.onelink.util.OnelinkContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-05-11
 */
@Slf4j
@RequiredArgsConstructor
public class FeignAuthTokenValidator implements FeignTokenValidator {

    private final FeignTokenEncryptor feignTokenEncryptor;

    @Override
    public boolean validate(String token) {
        if (token == null) {
            log.warn("[FeignToken] 内部接口鉴权失败, FeignToken为空");
            return false;
        }
        try {
            String decryptedToken = this.feignTokenEncryptor.decrypt(token);
            JSONObject tokenInfo = JSON.parseObject(decryptedToken);
            tokenInfo.forEach((k, v) -> OnelinkContextHolder.putIfAbsent(k, ObjectUtil.defaultIfNull(v, "").toString()));
        } catch (Exception e) {
            log.error("[FeignToken] 解密失败,Token={}", token);
        }
        return true;
    }

}
